using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine;

// 属性变化事件参数
public struct ModelPropertyChangedEventArgs
{
    public string PropertyName { get; private set; }
    public object OldValue { get; private set; }
    public object NewValue { get; private set; }
    public Model Target { get; private set; }
    
    public ModelPropertyChangedEventArgs(string propertyName, object oldValue, object newValue, Model target = null)
    {
        PropertyName = propertyName;
        OldValue = oldValue;
        NewValue = newValue;
        Target = target;
    }
}

// Model基类 (用于承载玩家数据)
// 所有Model都继承自该类
// Model的生命周期是全局的
public class Model
{
    // 属性变化事件
    public event Action<ModelPropertyChangedEventArgs> PropertyChanged;
    
    // 属性变化通知方法
    protected virtual void OnPropertyChanged(string propertyName, object oldValue, object newValue)
    {
        PropertyChanged?.Invoke(new ModelPropertyChangedEventArgs(propertyName, oldValue, newValue, this));
    }
    
    // 便捷的属性设置方法
    protected bool SetProperty<T>(ref T field, T value, string propertyName)
    {
        if (EqualityComparer<T>.Default.Equals(field, value))
            return false;
            
        var oldValue = field;
        field = value;
        OnPropertyChanged(propertyName, oldValue, value);
        return true;
    }
    
    // 添加属性变化监听器
    public void AddPropertyChangedListener(Action<ModelPropertyChangedEventArgs> listener)
    {
        PropertyChanged += listener;
    }
    
    // 移除属性变化监听器
    public void RemovePropertyChangedListener(Action<ModelPropertyChangedEventArgs> listener)
    {
        PropertyChanged -= listener;
    }
    
    // 清除所有监听器
    public void ClearPropertyChangedListeners()
    {
        PropertyChanged = null;
    }
}

// Model管理器
// 管理所有Model
public class ModelManager {
    // Model字典
    private Dictionary<Type, Model> _models = new Dictionary<Type, Model>();

    // 单例
    private static ModelManager _instance;
    public static ModelManager Instance {
        get {
            if (_instance == null)
            {
                _instance = new ModelManager();
            }
            return _instance;
        }
    }

    // 提供一个静态方法，快捷访问
    public static T GetModel<T>() where T : Model, new() {
        return Instance.GetOrNewModel<T>();
    }

    // 注册模型
    private void RegisterModel<T>(T model) where T : Model {
        _models.Add(typeof(T), model);
    }

    // 获取模型
    // 如果模型不存在，则创建模型并注册
    private T GetOrNewModel<T>() where T : Model, new() {
        if (_models.TryGetValue(typeof(T), out var model)) {
            // 类型校验, 防止类型不匹配
            if (model.GetType() != typeof(T)) {
                throw new Exception("Model类型不匹配");
            }
            return (T)model;
        }
        
        // 通过类型创建模型
        var newModel = new T();
        RegisterModel(newModel);
        return newModel;
    }
}